<script setup>
import TopButtonCenter from "@/components/Pengyq/TopButtonCenter.vue";
import { ItemShopStore } from "@/stores/ItemAnShop";
import { useUseStore } from "@/stores/user";
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  getNoPidOrder,
  approve,
  complete,
  cancelled,
} from "@/server/api/rechargeOrder";
import { getJWTFun } from "@/hook/jsrsasign";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const backgroundColor = [
  "linear-gradient(227deg, rgb(251 252 82 / 43%) 0%, rgb(255 255 255 / 0%) 100%), linear-gradient(134deg, rgb(254 226 134 / 74%) 0%, rgba(241, 246, 245, 0) 100%)",
  "linear-gradient(225.83deg, rgba(168, 255, 236, 0.43) 0%, rgba(245, 245, 245, 0) 100%), linear-gradient(147.41deg, rgba(211, 209, 255, 1) 0%, rgba(245, 245, 245, 0) 100%",
];

/*
&注册区
*/
const ItemShop = ItemShopStore();
const useStore = useUseStore();
const route = useRoute();
const router = useRouter();
const orderId = ref(""); //定义订单id
const price = route.query.value * 6; //定义余额总数item
let uid = useStore.userId;

// // 设置JWT有效载荷
let payload = ref({
  uid,
  exp: Math.floor(Date.now() / 1000) + 600, // 过期时间（当前时间戳加10分钟）
});

/*
&函数区
*/
// 前端请求支付授权,在本地订单创建后调
const rechargeFun = async () => {
  // 生成token
  let token = getJWTFun(payload.value);

  // 后端生成pi币充值的未支付订单，并返回订单的id
  let { data } = await getNoPidOrder(token);

  // 订单id
  let rechargeOrderId = data.data;
  if (rechargeOrderId) {
    console.log("订单创建成功,订单id:" + rechargeOrderId);
  }

  // pi创建订单方法
  Pi.createPayment(
    // 初始化，订单信息
    {
      amount: 3.14,
      memo: t('order.memo'),
      metadata: { productID: "apple_pie_1" },
    },

    {
      // pi官方的内置方法 授权
      async onReadyForServerApproval(paymentId) {
        console.log("paymentId", paymentId);

        // 暂时写死数据测试
        let { data } = await approve({
          amount: 3.14,
          paymentId,
          rechargeOrderId,
        });

        console.log(data);
      },

      // pi支付成功回调
      onReadyForServerCompletion: (paymentId, txId) => {
        // 支付成功请求体
        let completeReq = {
          rechargeOrderId,
          paymentId,
          txId,
        };

        // 支付成功的后端接口
        complete(completeReq).then((data) => {
          console.log(data);
        });
      },

      //支付取消
      onCancel: () => {
        cancelled(rechargeOrderId).then(({ data }) => {
          console.log(data);
        });
      },

      //支付失败
      onError: (error, payment) => {
        console.log("error:", error);
        console.log("payment:", payment);
      },
    }
  );
};

onMounted(() => {
  payload.value.point_amount = Number(route.query.point_amount);
  payload.value.pi_sum = Number(route.query.pi_sum);
});
</script>

<template>
  <!-- 主体模块 -->
  <main class="payOrders">
    <div class="top">
      <top-button-center :title="$t('order.confirmOrder')" style="background-color: transparent" />
    </div>

    <div class="card" :style="{
      padding: '40rem 10rem 10rem 10rem',
      background:
        ItemShop.IdtStatus == 'item'
          ? backgroundColor[0]
          : backgroundColor[1],
      color: '#829',
      fontWeight: 600,
      fontSize: '25rem',
    }">
      Once the payment is successful, you can proceed
    </div>

    <div class="card integral">
      <div class="title">{{ $t("order.piPay") }}</div>
      <span><van-icon name="checked" color="#642e8e" /></span>
    </div>

    <div class="card content">
      <div class="item" v-if="route.query.value">
        <div class="title">{{ $t("order.total") }}</div>
        <span>{{ route.query.value }}</span>
      </div>

      <div class="item" v-if="payload">
        <div class="title">{{ $t("order.payable") }}</div>
        <span>{{ payload.point_amount }}</span>
      </div>
    </div>

    <div class="card integral">
      <div class="title">{{ $t("order.total") }}</div>

      <span style="color: #642e8e" v-if="payload">
        {{ payload.point_amount }}
      </span>
    </div>

    <footer>
      <div class="pay" @click="rechargeFun">{{ $t("order.submit") }}</div>
    </footer>
  </main>
</template>

<style lang="scss" scoped>
.payOrders {
  padding: 50rem 10rem 10rem;
  font-size: 14rem;
  background-color: #f5f5f5;
  height: 100vh;

  >.top {
    position: fixed;
    z-index: 1000;
    background-color: #f5f5f5;
    top: 0;
    left: 0;
    right: 0;
  }

  .card {
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    padding: 10rem;
    margin-top: 20rem;
    width: 100%;
    height: 140rem;
    background-color: #fff;
    border-radius: 10rem;

    h5 {
      font-size: 20rem;
      font-weight: 500;
    }

    .bottom {
      display: flex;
      justify-content: space-between;
      margin-top: auto;

      .tex {
        color: #ddd;
        width: 40rem;
        text-align: center;
        line-height: 30rem;
      }

      .addCart {
        padding-left: 20rem;
        color: #4e4e4e;
        margin-left: auto;

        .total {
          b {
            font-size: 16rem;
          }
        }
      }
    }

    .title {
      font-size: 18rem;
      display: flex;
      justify-content: space-between;
    }
  }

  .integral {
    height: 60rem;
    font-size: 18rem;
    font-weight: 530;
    display: flex;
    justify-content: space-between;
    padding: 20rem 10rem;
    flex-direction: row;
  }

  .content {
    padding: 20rem 10rem;
    height: auto;

    .item {
      line-height: 50rem;
      display: flex;
      justify-content: space-between;
    }
  }
}

footer {
  .pay {
    position: fixed;
    bottom: 0rem;
    left: 0;
    right: 0;

    margin: 0 16rem 20rem;

    text-align: center;
    height: 40rem;
    line-height: 40rem;
    color: #fff;
    background-color: #642e8e;
    border-radius: 5rem;
    font-size: 16rem;
  }
}
</style>
